package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.iot.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-23
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        return deviceDataMapper.selectDeviceDataList(dto);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Autowired
    private DeviceMapper deviceMapper;
    /**
     * 批量保存数据
     * @param iotMsgNotifyData
     */
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1. 解析上报的数据，获取设备Id
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        //2. 根据设备Id查询设备，判断设备是否存在
        LambdaQueryWrapper<Device> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Device::getIotId,deviceId);
        Device device = deviceMapper.selectOne(lqw);
        //3. 设备不存在，则直接结束，继续处理下一条消息
        if(device == null){
            log.error("设备不存在，iotId:{}",deviceId);
            return;
        }
        //4. 设备存在，则构建数据，并插入数据库,一个设备可以有多个service

        iotMsgNotifyData.getBody().getServices().forEach(s -> {
            String serviceId = s.getServiceId();
            //将UTC时间字符，转换成我们需要的 时间字符
            //处理上报时间日期
            LocalDateTime eventTime =  LocalDateTimeUtil.parse(s.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //新建一个list,用来封装批量保存数据库的数据
            List<DeviceData> list = new ArrayList<>();
            Map<String, Object> properties = s.getProperties();
            properties.forEach((key,value)->{
                DeviceData deviceData = new DeviceData();
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setIotId(device.getIotId());
                deviceData.setProductKey(device.getProductKey());
                deviceData.setProductName(device.getProductName());
                deviceData.setLocationType(device.getLocationType());
                deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                deviceData.setFunctionId(key);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);
                deviceData.setRemark(key);
                list.add(deviceData);
            });
            saveBatch(list);
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(list));
        });

        //最后处理缓存
        // 为了小程序查询家人健康功能，这里先把这个iot消息，存到redis缓存里，
        //在小程序后端中解析后返回给前端，这样就避免了操作数据库，同时也解决了数据库字段不全，官网接口不合适的问题
        String jsonStr = JSONUtil.toJsonStr(iotMsgNotifyData);
        String deviceName = device.getDeviceName();
        redisTemplate.opsForValue().set("iot:"+deviceName, jsonStr);

    }


}
